var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// 引入cors - 解决跨域的模块
var cors = require('cors');


// 路由设置 - 引入路由模块
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var usersAddressesRouter = require('./routes/user_addresses');
var orderItemsRouter = require('./routes/order_items');
var ordersRouter = require('./routes/orders');
var productReviewsRouter = require('./routes/product_reviews');
var productSpecsRouter = require('./routes/product_specs');
var productsRouter = require('./routes/products');
var shoppingCartRouter = require('./routes/shopping_cart');
var systemConfigsRouter = require('./routes/system_configs');
var userCouponsRouter = require('./routes/user_coupons');
var userLoginLogsRouter = require('./routes/user_login_logs');
var bannersRouter = require('./routes/banners');
var brandsRouter = require('./routes/brands');
var categoriesRouter = require('./routes/categories');
var couponsRouter = require('./routes/coupons');
var searchRouter = require('./routes/search');
var imagesRouter = require('./routes/images');

var app = express();


// 使用cors
app.use(cors());

// view engine setup || 查看引擎设置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use(express.static(path.join(__dirname, 'uploads')));|| 上传文件
//路由设置 - 注册路由
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/user_addresses', usersAddressesRouter);
app.use('/order_items', orderItemsRouter);
app.use('/orders', ordersRouter);
app.use('/product_reviews', productReviewsRouter);
app.use('/product_specs', productSpecsRouter);
app.use('/products', productsRouter);
app.use('/shopping_cart', shoppingCartRouter);
app.use('/system_configs', systemConfigsRouter);
app.use('/user_coupons', userCouponsRouter);
app.use('/user_login_logs', userLoginLogsRouter);
app.use('/banners', bannersRouter);
app.use('/brands', brandsRouter);
app.use('/categories', categoriesRouter);
app.use('/coupons', couponsRouter);
app.use('/search', searchRouter);
app.use('/images', imagesRouter);

// catch 404 and forward to error handler || 捕获404并转发到错误处理程序
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler || 错误处理程序
app.use(function(err, req, res, next) {
  // set locals, only providing error in development || 设置局部变量，仅在开发环境提供错误
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page || 呈现错误页面
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
